import {
  loginByCode,
  allNetwork,
  systematicsList
} from "../../../api.js"
var app = getApp().globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isAuth: false,
    allSubmitInfo: {
      full_name: '', //商品名称（模糊搜索）
      category_id: [], //商品大类id
      page: 1, //页码（默认1 禁止传0）
      last_page: 1,
      brand_name: '', //品牌名
      time_sort: 0, //最新时间 1 降序 2升序
      peer_price: 0, //价格排序 1 降序 2升序
      price: 0, //价格排序 1 降序 2升序
      singlepage: 10, //单页条数（默认20）
    },
    icon_img: [ 
      'http://document.growthupup.com/arrow-top.png', 
      'http://document.growthupup.com/arrow-bottom.png', 
      'http://document.growthupup.com/filtrate@2x.png'
    ],
    filter_typ:false,
    clickAllId: '', //全网库存选择大类判断
    allProductItems:[],
    app_user:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.checkUserInfo()
  },
  // 检查用户信息授权
  checkUserInfo() {
    const xp = this;
    wx.getSetting({
      success: function(res) {
        if (!res.authSetting['scope.userInfo']) {
          xp.setData({
            isAuth: true
          })
        } else {
          xp.setData({
            isAuth: false
          })
          wx.getUserInfo({
            success(res) {
              xp.logToken(res.userInfo)
            }
          })
        }
      }
    })
  },
  //获取token
  logToken(userInfo) {
    var that = this
    wx.login({
      success(res) {
        loginByCode(res.code, { ...userInfo
        }).then(res => {          
          if (res.data.code == 666) {
            app.userInfo = res.data.data
            that.homePage(res.data.data.token)
            that.setData({
              app_user: res.data.data
            })
            systematicsList({
              token: res.data.data.token
            }).then(res =>{
              res.data.data.forEach(function (item) {
                item.bol = false
              })
              that.setData({
                productCate: res.data.data,
              })
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        })
      }
    })
  },
  homePage(token){
    var that = this
    allNetwork(token, {
      ...that.data.allSubmitInfo
    }).then(res => {
      console.log(res)
      let data;
      if (res.data.data) {
        data = res.data.data.data
      } else {
        data = [];
      }
      that.setData({
        allProductItems: data,
        'allSubmitInfo.page': res.data.data ? res.data.data.current_page : 1,
        'allSubmitInfo.last_page': res.data.data ? res.data.data.last_page : 1,
      })
    })
  },
  //授权按钮
  handleUserInfoGet(res) {
    this.checkUserInfo()
  },
  bindSearch(e) {
    this.setData({
      'submitInfo.full_name': e.detail.value
    })
  },
  //搜索
  searchProduct(e) {
    const _this = this;
    _this.setData({
      'allSubmitInfo.full_name': e.detail.value,
    })
    this.homePage(app.userInfo.token);
  },
  closed() {
    console.log('关闭')
    this.setData({
      'submitInfo.full_name': ''
    })
  },
  lastest(){
    var that = this
    var form = that.data.allSubmitInfo
    if (form.time_sort == 0){
      form.time_sort = 1
    } else if (form.time_sort == 1){
      form.time_sort = 2
    }else{
      form.time_sort = 1
    }
    form.full_name = ''
    form.category_id = ''
    form.page = 1
    form.brand_name = ''
    form.peer_price = 0
    form.price = 0
    that.setData({
      allSubmitInfo:form
    })
    that.homePage(app.userInfo.token)
  },
  priceSort(){
    var that = this
    var form = that.data.allSubmitInfo
    if (form.price == 0) {
      form.price = 1
    } else if (form.price == 1) {
      form.price = 2
    } else {
      form.price = 1
    }
    form.full_name = ''
    form.category_id = ''
    form.page = 1
    form.brand_name = ''
    form.time_sort = 0
    that.setData({
      allSubmitInfo: form
    })
    that.homePage(app.userInfo.token)
  },
  priceSort_peer(){
    var that = this
    var form = that.data.allSubmitInfo
    if (form.peer_price == 0) {
      form.peer_price = 1
    } else if (form.peer_price == 1) {
      form.peer_price = 2
    } else {
      form.peer_price = 1
    }
    form.full_name = ''
    form.category_id = ''
    form.page = 1
    form.brand_name = ''
    form.time_sort = 0
    that.setData({
      allSubmitInfo: form
    })
    that.homePage(app.userInfo.token)
  },
  allFilterate(){
    this.setData({
      filter_typ:true
    })
  },
  chooseCate(e) {
    const _this = this;
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    let category_id = _this.data.allSubmitInfo.category_id;
    let bol = 'productCate[' + index + '].bol';
    _this.setData({
      clickAllId: id,
      [bol]: (_this.data.productCate[index].bol == true) ? false : true,
    })
  },
  filter(){
    this.setData({
      filter_typ: false
    })
  },
  filter_pinp(){
    wx.navigateTo({
      url: '/pages/mylist/productBrands/productBrands?type=1'
    })
  },
  down(){
    this.fetchData2(this.data.allSubmitInfo.page + 1, 'up')
  },
  fetchData2(start, direction) {
    const _this = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    _this.setData({
      'allSubmitInfo.page': start
    })
    let allSubmitInfo = _this.data.allSubmitInfo;
    // allSubmitInfo.token = app.userInfo.token;
    allNetwork(app.userInfo.token,{...allSubmitInfo}).then(res => {
      if (res.data.code == 666) {
        let allProductItems = _this.data.allProductItems;
        if (direction == 'up') {
          allProductItems = allProductItems.concat(res.data.data.data)
        } else {
          allProductItems = res.data.data.data
        }
        _this.setData({
          allProductItems,
          'allSubmitInfo.page': res.data.data.current_page,
          'allSubmitInfo.last_page': res.data.data.last_page,
        })
        wx.hideLoading();
        wx.stopPullDownRefresh();
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          mask: true,
        })
      }
    })
  },
  confirm(){
    const _this = this;
    _this.setData({
      selected2: 0,
      'allSubmitInfo.full_name': '', //商品名称（模糊搜索）
      'allSubmitInfo.peer_price': 0, //价格排序 1 降序 2升序
      'allSubmitInfo.time_sort': 0, //最新时间 1 降序 2升序
      'allSubmitInfo.shares_sort': 0, //分享 1 降序 2升序
      'allSubmitInfo.cart_count_sort': 0, //加购 1 降序 2升序
      filter_typ:false
    })
    _this.data.allSubmitInfo.category_id = []
    _this.data.productCate.forEach(function (item) {
      if (item.bol == true) {
        _this.data.allSubmitInfo.category_id.push(item.id)
      }
    })
    _this.homePage(app.userInfo.token);
  },
  toBuy(e) {
    let id = e.currentTarget.dataset.id;
    let price = e.currentTarget.dataset.price;
    let picture_list = e.currentTarget.dataset.picture;
    let deliver = e.currentTarget.dataset.deliver;
    let full_name = e.currentTarget.dataset.fullName.replace(/\&/g, '@');
    let is_synchronize = e.currentTarget.dataset.is_synchronize
    wx.navigateTo({
      url: '/pages/public/toBuy/toBuy?id=' + id + '&is_synchronize=' + is_synchronize,
    })
  },
})